package max.ubitest.pipe.commands
{
	import max.ubitest.pipe.data.CellData;
	import max.ubitest.pipe.data.ComponentData;
	import max.ubitest.pipe.data.ComponentTypes;
	import max.ubitest.pipe.data.ReservoirSideComponentData;
	import max.ubitest.pipe.events.PipeEvent;
	import max.ubitest.pipe.locators.CellLocator;
	import max.ubitest.pipe.locators.ComponentsLocator;
	
	import org.robotlegs.mvcs.Command;
	
	public class ClickCellCommand extends Command
	{
		[Inject]
		public var event:PipeEvent;
		[Inject]
		public var locator:ComponentsLocator;
		[Inject]
		public var cellLocator:CellLocator;
		
		public function ClickCellCommand()
		{
			super();
		}
		
		override public function execute():void{
			if(locator.selectedComponent == null){
				return;
			}
			if(isCellEmpty()){
				if(locator.selectedComponent){
					//map selected component data
					if(locator.selectedComponent.type == ComponentTypes.RESERVOIR){
						//set around cells as ReservoirSideCell
						var v:Vector.<CellData> = cellLocator.getCellsAround(event.data as CellData);
						for each(var cell:CellData in v){
							cell.componentData = new ReservoirSideComponentData({cellData:event.data});
						}
					}
					
					event.data.componentData = locator.selectedComponent;
					locator.selectedComponent.cellData = event.data as CellData;
					locator.mappedComponents.addItem(event.data);
					locator.selectedComponent = null;
					
					var validEvent:PipeEvent = new PipeEvent(PipeEvent.DO_VALIDATION, null);
					dispatch(validEvent);
				}
			}
		}
		
		private function isCellEmpty():Boolean{
			var cd:ComponentData = event.data.componentData as ComponentData;
			if(locator.selectedComponent.type != ComponentTypes.RESERVOIR){
				if(cd == null){
					return true;
				}else{
					return false;
				}
			}else{
				var v:Vector.<CellData> = cellLocator.getCellsAround(event.data as CellData);
				if(v.length < 8){
					return false;
				}else{
					var result:Boolean = true;
					for each(var cell:CellData in v){
						if(cell.componentData){
							result = false;
							break;
						}
					}
					return result;
				}
			}
		}
	}
}